package com.example.paymentsystem.template;

import com.example.paymentsystem.common.PaymentRequest;
import com.example.paymentsystem.common.PaymentResponse;
import com.example.paymentsystem.observer.PaymentEvent;
import com.example.paymentsystem.observer.PaymentEventPublisher;
import com.example.paymentsystem.strategy.PaymentContext;

/**
 * @author YiYuan
 * @data 2025/6/25
 * @apoNote
 */
public abstract class AbstractPaymentTemplate {

    private PaymentContext context;

    private PaymentEventPublisher publisher;

    public final PaymentResponse processPayment(PaymentRequest request) {

        // 1. 校验订单
        validateOrder(request);

        // 2. 校验金额
        validateAmount(request);

        // 3. 执行支付
        PaymentResponse response = doPay(request);

        // 4. 支付后逻辑
        afterPayment(request, response);

        publisher.publish(new PaymentEvent(request, response));

        return response;
    }

    protected void validateOrder(PaymentRequest request) {
        System.out.println("Validating order for: " + request.getOrderId());

        if (request.getOrderId() == null || request.getOrderId().isEmpty()) {
            throw new IllegalArgumentException("Order ID cannot be empty.");
        }
    }

    protected void validateAmount(PaymentRequest request) {
        System.out.println("Validating amount for: " + request.getAmount());

        if (request.getAmount() <= 0) {
            throw new IllegalArgumentException("Amount must be positive.");
        }
    }

    protected PaymentResponse doPay(PaymentRequest request) {
        return context.executePayment(request);
    }

    protected void afterPayment(PaymentRequest request, PaymentResponse response) {
        System.out.println("Payment process finished. Triggering notifications...");
    }

}
